<?php

namespace mpend\modules\passport\controllers;

use Yii;
use mpend\components\Controller;
use mpend\modules\passport\models\LoginForm;
use mpend\modules\passport\models\SmsLoginForm;

/**
 * 账号登录
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class LoginController extends Controller {

    /**
     * @inheritdoc
     */
    protected function verbs() {
        return [
            '*' => ['POST'],
        ];
    }

    /**
     * 帐号密码登录
     * @inheritdoc
     */
    public function actionIndex() {
        $model = new LoginForm();
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('请输入帐号和密码信息');
        }
        $model->token = $this->token;
        return $model->login();
    }

    /**
     * 短信验证码登录
     * @inheritdoc
     */
    public function actionSms() {
        $model = new SmsLoginForm();
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('请输入手机号和短信验证码');
        }
        $model->token = $this->token;
        return $model->login();
    }

    /**
     * {@inheritdoc}
     */
    public function afterAction($action, $result) {
        if (!$this->token->bindUser($result->id)) {
            parent::error('登录失败', $this->token->firstErrors);
        }
        $this->token->joinBranch($result->id);
        return parent::afterAction($action, $result);
    }

}
